package com.iot.ammeter.service.impl.web.provider;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.iot.ammeter.constant.Constant;
import com.iot.ammeter.dto.web.provider.ProviderDTO;
import com.iot.ammeter.dto.web.provider.ProviderIdNameDTO;
import com.iot.ammeter.entity.web.provider.Provider;
import com.iot.ammeter.exception.BusinessExceptions;
import com.iot.ammeter.mapper.web.provider.ProviderMapper;
import com.iot.ammeter.service.web.provider.ProviderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iot.ammeter.utils.CheckTool;
import com.iot.ammeter.utils.SnowFlakeIdWorker;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 属服务商，组织 服务实现类
 * </p>
 *
 * @author basil
 * @since 2021-09-25
 */
@Service
public class ProviderServiceImpl extends ServiceImpl<ProviderMapper, Provider> implements ProviderService {

    private final SnowFlakeIdWorker snowFlakeIdWorker;
    private final ProviderMapper providerMapper;

    public ProviderServiceImpl(SnowFlakeIdWorker snowFlakeIdWorker, ProviderMapper providerMapper) {
        this.snowFlakeIdWorker = snowFlakeIdWorker;
        this.providerMapper = providerMapper;
    }

    /**
     * 添加服务商
     *
     * @param providerDto 服务商信息
     * @return 添加成功或者添加失败提示
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String addProvider(ProviderDTO providerDto) {
        /**
         * 实体校验
         */
        String province = providerDto.getProvince().trim();
        String city = providerDto.getCity().trim();
        String area = providerDto.getArea().trim();
        String providerAddress = providerDto.getProviderAddress().trim();
        String contactPerson = providerDto.getContactPerson().trim();
        String phone = providerDto.getPhone().trim();
        String email = providerDto.getEmail().trim();
        if (StringUtils.isEmpty(province) || StringUtils.isEmpty(city) ||
                StringUtils.isEmpty(area) || StringUtils.isEmpty(providerAddress) ||
                StringUtils.isEmpty(contactPerson) || StringUtils.isEmpty(phone) ||
                StringUtils.isEmpty(email)) {
            throw new BusinessExceptions("服务商信息存在空字段");
        }
        if (!CheckTool.isPhone(phone)) {
            throw new BusinessExceptions("手机号码非法");
        }
        if (!CheckTool.isEmail(email)) {
            throw new BusinessExceptions("邮箱格式有误");
        }
        /**
         * 复制补全数据
         */
        Provider providerToDb = new Provider();
        providerToDb.setProviderId(String.valueOf(snowFlakeIdWorker.nextId()));
        providerToDb.setProvince(province);
        providerToDb.setCity(city);
        providerToDb.setArea(area);
        providerToDb.setProviderAddress(providerAddress);
        providerToDb.setProviderName(area + "服务商");
        providerToDb.setContactPerson(contactPerson);
        providerToDb.setPhone(phone);
        providerToDb.setEmail(email);
        providerToDb.setCreateTime(LocalDateTime.now());
        providerToDb.setUpdateTime(LocalDateTime.now());
        providerToDb.setProviderStatus(0);
        /**
         * 添加至数据库
         */
        int result = providerMapper.insert(providerToDb);
        return result > 0 ? "添加服务商成功" : "添加服务商失败";
    }

    /**
     * 获取所有的服务商
     *
     * @return 返回所有服务商列表
     */
    @Override
    public List<ProviderDTO> getProviderList() {
        List<ProviderDTO> providerDTOList = providerMapper.listAllProvider();
        return providerDTOList;
    }

    /**
     * 获取服务商id和名称
     *
     * @return 服务商id和名称集合
     */
    @Override
    public List<ProviderIdNameDTO> getProviderIdAndName() {
        /**
         * 获取所有服务商
         */
        LambdaQueryWrapper<Provider> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Provider::getProviderStatus, Constant.Provider.NORMAL);
        /**
         * 只查询服务商id和名称
         */
        queryWrapper.select(Provider::getProviderId, Provider::getProviderName);
        List<Provider> providers = providerMapper.selectList(queryWrapper);
        if (providers.isEmpty()) {
            return null;
        }
        List<ProviderIdNameDTO> providerList = new ArrayList<ProviderIdNameDTO>();
        ProviderIdNameDTO providerTemplate = null;
        /**
         * 忽略字段
         */
        String[] strings = {"province", "city", "area", "providerAddress",
                "contactPerson", "phone", "email", "remark", "createTime", "updateTime", "providerStatus"};
        /**
         * 数据装换。
         */
        for (Provider provider : providers) {
            providerTemplate = new ProviderIdNameDTO();
            BeanUtils.copyProperties(provider, providerTemplate, strings);
            providerList.add(providerTemplate);
        }
        return providerList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String deleteProvider(List<String> providerIds) {
        if (providerIds.isEmpty()) {
            throw new BusinessExceptions("服务商id不能为空。");
        }
        //查看服务商下是否有用户，有则删除失败
        Integer count = providerMapper.selectCountProviderWebUser(providerIds);
        if (count > 0) {
            throw new BusinessExceptions("删除失败，服务商下存在用户。");
        }
        return providerMapper.deleteBatchIds(providerIds) > 0 ? "删除成功。" : "删除失败。";
    }

}
